package web.servlet;

import utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/demo5")
public class CookieTimeDemo5 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //判断是否是第一次访问，依据是查看这次请求是否有我们记录上次时间的cookie (name:lastVisit)

        //获取指定名称cookie
        Cookie[] cookies = req.getCookies();
        Cookie lastVisitCookie = CookieUtils.findCookie(cookies,"lastVisit");

        //判断
        if (lastVisitCookie == null){
            //首次访问
            resp.getWriter().write("欢迎首次访问!");
        }else{
            //非首次访问 (之前向浏览器响应回去的cookie值为访问时间的毫秒值，这里获取的就是一个毫秒值字符串)
            String lastTime = lastVisitCookie.getValue();
            long millis = Long.parseLong(lastTime);
            Date date = new Date(millis);
            String timeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            resp.getWriter().write("欢迎回来,您的上次访问时间为：" + timeStr);
        }

        //将最新的时间响应到浏览器（回写cookie）
        lastVisitCookie = new Cookie("lastVisit",System.currentTimeMillis()+"");
        lastVisitCookie.setMaxAge(60*60*24*7);
        lastVisitCookie.setPath(req.getContextPath());
        resp.addCookie(lastVisitCookie);
    }
}
